<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Admin\Traits\AdminTrait;
use App\Http\Requests\Admin\BaseRequest;
use App\Models\Admin\AdminListField;
use App\Models\Admin\Company;
use App\Models\Admin\CompanyType;
use App\Models\Admin\Goods;
use App\Models\Admin\ListField;
use App\Models\Admin\Member;
use App\Models\Admin\OperateLogs;
use App\Models\Admin\SendTime;
use App\User;
use Illuminate\Support\Arr;
use Illuminate\Support\Carbon;
//use App\Models\Admin\DispatchOrder as Order;
use App\Models\Admin\Order;
//use App\Models\Admin\DispatchOrderList as OrderList;
use App\Models\Admin\OrderList;
use Saas,Auth,DB;
use Illuminate\Http\Request;

class OrderController extends AdminController
{
    use AdminTrait;

    protected $model;

    /**
     * 定义验证规则
     */
    protected $validate_rule = [
    ];

    /**
     * 定义验证错误信息
     */
    protected $err_msg = [
    ];


    /**
     * 定义列表排序
     */
    protected $orderBy = [
        'id' => 'desc',
    ];

    protected $order_status = [
        Order::ORDER_REVIEW => '待支付',
        Order::ORDER_STOCK_UP => '备货中',
        Order::ORDER_SHIPPED => '配送中',
        Order::ORDER_COMPLETED => '已收货',
        Order::ORDER_CANCELLED => '已取消',
    ];

    public function __construct(Order $model)
    {
        parent::__construct();
        $this->model = $model;
    }

    protected function beforeIndex()
    {
        $fromList = [
            0=>'后台',
            1=>'公众号',
            2=>'小程序',
            3=>'PC',
            4=>'APP'
        ];
        //$group = Group::pluck('title','id');
        $pay_type_list = [0=>'未支付',1=>'已支付'];
        $is_print_list = [0=>'未打印',1=>'已打印'];
//        $send_time = SendTime::selectRaw('CONCAT_WS("-",start_time,end_time) as times,id')->pluck('times','id')->toArray();
        $field = AdminListField::getListField(5);

        $today_order_num = $this->model->whereRaw("FROM_UNIXTIME(created_at,'%Y-%m-%d')='".date('Y-m-d')."'")->where('order_status','<',Order::ORDER_CANCELLED)->count();
        $today_order_money = $this->model->whereRaw("FROM_UNIXTIME(created_at,'%Y-%m-%d')='".date('Y-m-d')."'")->where('order_status','<',Order::ORDER_CANCELLED)->sum('order_money');

        $today_send_num = $this->model->whereRaw("FROM_UNIXTIME(send_time,'%Y-%m-%d')='".date('Y-m-d')."'")->where('order_status','<',Order::ORDER_CANCELLED)->count();
        $today_send_order_money = $this->model->whereRaw("FROM_UNIXTIME(send_time,'%Y-%m-%d')='".date('Y-m-d')."'")->where('order_status','<',Order::ORDER_CANCELLED)->sum('order_money');
        $today_send_money = $this->model->whereRaw("FROM_UNIXTIME(send_time,'%Y-%m-%d')='".date('Y-m-d')."'")->where('order_status','<',Order::ORDER_CANCELLED)->sum('send_money');

        $today_sent_num = $this->model->whereRaw("FROM_UNIXTIME(send_time,'%Y-%m-%d')='".date('Y-m-d')."'")->whereIn('order_status',[Order::ORDER_SHIPPED,Order::ORDER_COMPLETED])->count();

        $company_type=CompanyType::pluck('name','id');
        return [
            'order_status'=>$this->order_status,
            'fromList'=>$fromList,
            //'group'=>$group,
            'pay_type_list'=>$pay_type_list,
            'send_time'=>[],
            'is_print_list'=>$is_print_list,
            'field'=>$field,
            'today_order_num'=>$today_order_num,
            'today_order_money'=>$today_order_money,
            'today_send_num' => $today_send_num,
            'today_send_order_money' => $today_send_order_money,
            'today_send_money' => $today_send_money,
            'today_sent_num' => $today_sent_num,
            'company_type' => $company_type,
        ];
    }

    protected function search($request)
    {
//        $nickname = $request->query('nickname','');
        $company_id = $request->company_id;
        $name = $request->query('name','');
        $start_time = $request->query('start_time','');
        $end_time = $request->query('end_time','');
        $create_start_time = $request->query('create_start_time','');
        $create_end_time = $request->query('create_end_time','');
        $pay_type = $request->query('pay_type','');
        //$group_id = $request->query('group_id',0);
        $look_canceled_list = $request->query('look_canceled_list',0);
        $status = $request->query('status',0);
        $select = $this->model->with(['companyName']);
        ($pay_status = $request->query('pay_status',0)) && $select = $select->where('pay_status',$pay_status-1);
        ($from = $request->query('from',0)) && $select = $select->where('from',$from-1);
        ($is_print = $request->query('is_print',0)) && $select = $select->where('is_print',$is_print-1);
        ($company_type_id = $request->query('company_type_id',0)) && $select = $select->where('company_type',$company_type_id);
        ($mobile = $request->query('mobile','')) && $select = $select->where('mobile','like',"%$mobile%");
        ($send_time_id = $request->query('send_time_id',0)) && $select = $select->where('send_time_id',$send_time_id);
        ($order_sn = $request->query('order_sn','')) && $select = $select->where('order_sn','like',"%$order_sn%");
        ($contact = $request->query('contact','')) && $select = $select->where('contact','like',"%$contact%");
        if($pay_type){
            $select=$select->where('pay_type',$pay_type-1);
        }
        if (!$status){
            if ($look_canceled_list==0){
                $select = $select->where('order_status','!=',4);
            }
        }else{
            $select = $select->where('order_status',$status-1);
        }
        if ($start_time && $end_time){
            list($start_time_stamp,$end_time_stamp)=date_assemble($start_time,$end_time);
            $end_time_stamp=$end_time_stamp-1;
            $select = $select->whereBetween('send_time',[$start_time_stamp,$end_time_stamp]);
        }
        if ($create_start_time && $create_end_time){
            $select = $select->whereBetween('created_at',date_assemble($create_start_time,$create_end_time));
        }
//        if ($nickname){
//            //$uids = Member::where('nickname','like',"%$nickname%")->where('is_del',0)->where('pid',0)->pluck('id');
//            //$select = $select->whereIn('uid',$uids);
//            $company_uids = Company::where('company_name','like',"%$nickname%")->pluck('id');
//            $select = $select->whereIn('company_uid',$company_uids);
//        }
        if ($company_id){
            $select = $select->where('company_id',$company_id);
        }
        if($name){
            $goods_ids = Goods::orWhere('name','like',"%$name%")->orWhere('byname','like',"%$name%")->orWhere('pinyin','like',"%$name%")->orWhere('goods_code','like',"%$name%")->pluck('id');
            $oids = OrderList::whereIn('goods_id',$goods_ids)->pluck('oid');
            $select = $select->whereIn('id',$oids);
        }
        /*if ($group_id){
            $uids = MemberInfo::where('group_id',$group_id)->pluck('user_id');
            $select = $select->whereIn('uid',$uids);
        }*/
        return $select;
    }

    /* order/send_template post
     *  send_time string 2020-11-03
     *  send_time_id int
     *  order_list_status int
     *  order_status int
     *  nickname string
     *  print_status int
     */
    public function send_template(Request $request){
    {
        $send_time = $request->send_time;
        $nickname = $request->nickname;
        $select = $this->model->whereRaw("FROM_UNIXTIME(send_time,'%Y-%m-%d')='".$send_time."' and order_status in (1,2,3) ")->with(['companyName']);
        ($send_time_id = $request->send_time_id) && $select = $select->where('send_time_id',$send_time_id);
        ($order_list_status = $request->order_list_status) && $select = $select->where('order_list_status',$order_list_status-1);
        ($order_sn = $request->order_sn) && $select = $select->where('order_sn','like',"%$order_sn%");
        if($request->order_status==1){
            $select = $select->where('order_status',1);
        }
        if($request->order_status==2){
            $select = $select->whereIn('order_status',[2,3]);
        }
        if ($nickname){
            $company_uids = Company::where('company_name','like',"%$nickname%")->pluck('id');
            $select = $select->whereIn('company_uid',$company_uids);
        }
        $per_page = $request->per_page ?: 15;
        ($print_status = $request->print_status) && $select = $select->orderBy('is_print','asc');
        $list = $select->orderBy('order_status','asc')->orderBy('id','desc')->paginate($per_page);
        $sort_status = [
            0 => '未分拣',
            1 => '部分分拣',
            2 => '分拣完成',
        ];
        $order_status = [ //发货状态
            1 => '未发货',
            2 => '已发货',
        ];

        $send_time_list = SendTime::selectRaw('CONCAT_WS("-",start_time,end_time) as times,id')->pluck('times','id')->toArray();

        $all = $this->model->whereRaw("FROM_UNIXTIME(send_time,'%Y-%m-%d')='".$send_time."' and order_status in (1,2,3) ")->where('order_status','<',4)->count();
//        $all_un = $this->model->whereRaw("FROM_UNIXTIME(send_time,'%Y-%m-%d')='".$send_time."'")->where('order_status',1)->count();
        $all_ed = $this->model->whereRaw("FROM_UNIXTIME(send_time,'%Y-%m-%d')='".$send_time."'")->whereIn('order_status',[2,3])->count();
//        $all_ok = $this->model->whereRaw("FROM_UNIXTIME(send_time,'%Y-%m-%d')='".$send_time."'")->where('order_status',1)->where('order_list_status',2)->count();
        $all_print_over = $this->model->whereRaw("FROM_UNIXTIME(send_time,'%Y-%m-%d')='".$send_time."' and order_status in (1,2,3)" )->where('is_print',1)->count();
        $all_print_no = $this->model->whereRaw("FROM_UNIXTIME(send_time,'%Y-%m-%d')='".$send_time."' and order_status in (1,2,3)")->where('is_print',0)->count();

        return $this->success(['list'=>$list,'sort_status'=>$sort_status,'all'=>$all,'all_print_over'=>$all_print_over,'all_ed'=>$all_ed,'all_print_no'=>$all_print_no,'order_status'=>$order_status,'send_time_list'=>$send_time_list]);
    }
}
    public function base(BaseRequest $request)
    {
        $field = ListField::getListField(4);
        $send_time = SendTime::selectRaw('CONCAT_WS("-",start_time,end_time) as times,id')->pluck('times','id')->toArray();
        $display_sub_account = config('pin_setting.display_sub_account');
        $auto_merge_order = config('pin_setting.auto_merge_order');
        $show_sku_code = config('pin_setting.show_sku_code');
        $show_member_code = config('pin_setting.show_member_code');
        $users = User::with(['company','address'])->withoutGlobalScopes()->where('role_id',6)->get();
        $members = [];
        return $this->success(['display_sub_account'=>$display_sub_account,'send_time'=>$send_time,'field'=>$field,'members'=>$members,'auto_merge_order'=>$auto_merge_order,'show_sku_code'=>$show_sku_code,'show_member_code'=>$show_member_code,'user'=>$users]);
    }

    private function getMergeList($send_time,$uid,$zid=0,$is_prior_payment=0)
    {
        $send_time = strtotime($send_time);
        if (!$zid) $zid = 0;
        if (!$is_prior_payment) $is_prior_payment = 0;
        $list = $this->model->where('send_time',$send_time)->where('uid',$uid)->where('zid',$zid)->where('is_prior_payment',$is_prior_payment)->get();
        return $list;
    }
    private function splitAdd($info)
    {
        $orderInfo = $this->model->find($info->id);
        $orderList = OrderList::where('oid',$info->id)->get()->groupBy('pid')->toArray();
        if (count($orderList) <= 1){
            return true;
        }
        $orderList = array_splice($orderList,1);
        foreach ($orderList as $list){
            $newOrder = $orderInfo->replicate(['order_sn','delivery_fee','order_money']);
            $order_money = 0;
            foreach ($list as $val){
                $order_money = bcadd($order_money,bcmul($val['order_num'],$val['order_price'],2),2);
            }
            $newOrder->order_sn = $this->sn('DD');
            $newOrder->delivery_fee = 0;
            $newOrder->order_money = $order_money;
            $newOrder->save();

            $orderInfo->order_money = bcsub($orderInfo->order_money,$order_money,2);
            $orderInfo->save();

            $orderListId = collect($list)->pluck('id');
            OrderList::whereIn('id',$orderListId)->update(['oid'=>$newOrder->id]);
        }
    }
    private function mergeAdd($info,$ids)
    {
        $ids = json_decode($ids,true);
        array_push($ids,['id'=>$info->id]);
        $ids = Arr::pluck($ids,'id');

        //防止页面篡改
        $data = $this->model->with(['orderList'=>function($query){
            $query->select('id','oid','goods_id','goods_spu_id','order_num','order_price','sort_num','sort_price');
        }])->whereIn('id', $ids)->select('id','uid','zid','order_status','order_sn','send_time','order_money','send_money')->oldest('id')->get();
        if($data->count() <= 1){
            return ['40037','单个订单无法合并'];
        }
        $first = $data->shift();
        $first->send_carbon = Carbon::createFromTimestamp($first->send_time);

        $errors = [];
        $delOls = collect([]);
        $data->each(function($item) use(&$first,&$errors,&$delOls){
            if($item->order_status > 1){
                $errors = ['40038','订单不是待审核和备货中状态，无法合并'];
                return false;
            }
            if($item->uid != $first->uid || $item->zid != $first->zid){
                $errors = ['40039','订单不是同一个用户的，无法合并'];
                return false;
            }

            $item->send_time = Carbon::createFromTimestamp($item->send_time);
            if(!$first->send_carbon->isSameDay($item->send_time)){
                $errors = ['40040','配送日期不是同一天，无法合并'];
                return false;
            }
            $item->orderList->each(function($val) use(&$first,&$delOls,&$errors){
                $info = $first->orderList->firstWhere('goods_spu_id',$val->goods_spu_id);
                if (!empty($info)){
                    $first->orderList->firstWhere('id',$info->id)->order_num += $val->order_num;
                    $first->orderList->firstWhere('id',$info->id)->sort_num += $val->sort_num;
                    $delOls->push($val->id);
                }else{
                    $first->orderList->push($val);
                }
                $first->order_money += $val->order_num * $val->order_price;
                $first->send_money += $val->sort_num * $val->sort_price;
            });
        });
        if(!empty($errors)){
            return $errors;
        }
        unset($first->send_carbon);

        $orderIds = $data->pluck('id');
        DB::transaction(function() use($delOls,$orderIds,$first){
            $first->orderList()->saveMany($first->orderList);
            $first->save();
            OrderList::destroy($delOls->toArray());
            Order::destroy($orderIds->toArray());
        },5);
        return true;
    }
    private function creditAdd($info)
    {
        $memberInfo = MemberInfo::where('user_id',$info->uid)->first();
        $credit = MemberCredit::where('user_id',$info->uid)->first();
        if (empty($credit)) return true;
        if (!$credit->status) return true;
        $order_money = $this->model->where('order_status','<',Order::ORDER_CANCELLED)->where('uid',$info->uid)->sum('order_money');

        if ($order_money > bcmul(bcdiv(config('pin_setting.forbid_order'),100,2),$credit->credit,2)){
            $memberInfo->credit_status = 2;
            $memberInfo->save();
        }elseif($order_money >bcmul(bcdiv(config('pin_setting.credit_notice'),100,2),$credit->credit,2)){
            $memberInfo->credit_status = 1;
            $memberInfo->save();
        }

        $credit->debt = $order_money;
        $credit->save();
    }

    public function add(BaseRequest $request)
    {
        $requestData = $request->all();
        if (!$request->auto_split_order && config('pin_setting.auto_merge_order') && !isset($requestData['merge_status'])){
            $list = $this->getMergeList($request->send_time,$request->uid,$request->zid,$request->is_prior_payment);
            if (!empty($list)){
                return response()->json(['errcode'=>40042,'errmsg'=>'可合并列表','list'=>$list]);
            }
        }
        //去除数组
        $data = $this->setRequestField($request->all());

        DB::beginTransaction();
        try{
            //执行添加操作
            $result = $this->model->create($data);
            //后置操作
            //if (method_exists($this, 'afterData')) {
            $arr = $this->afterData($result,$request->all());
            if (!$arr[0]){
                return $this->error($arr[1]);
            }
            //}
            if (method_exists($this->model,'addLog')){
                $this->model->addLog($result,[],1);
            }
            DB::commit();
            return response()->json(['errcode'=>0,'errmsg'=>'ok']);
        }catch (\Exception $e){
            report($e);
            DB::rollBack();
            return response()->json(['errcode'=>40006,'errmsg'=>'添加失败']);
        }
    }

    public function edit(BaseRequest $request)
    {

        isset($this->unique_id) && $this->unique_id = $request->id;

        if(true !== $msg = $this->validate_form($request)){
            //验证未通过
            return response()->json(['errcode'=>'40012','errmsg'=>$msg]);
        }

        //获取模型
        $info = $this->model->findOrFail($request->id);

        DB::beginTransaction();
        try{
            //赋值
            foreach ($this->setRequestField($request->all(),true) as $k=>$v){
                if(!is_array($v)){
                    $info->$k = $v;
                }
            }
            $perInfo = $info->getOriginal();//获取修改之前的字段
            //执行修改操作
            $info->save();
            $nextInfo = $info->getChanges();//获取修改之后的字段
            //后置操作
            //if (method_exists($this, 'afterData')) {
            $arr = $this->afterData($info,$request->all());
            //}
            if (!$arr[0]){
                return $this->error($arr[1]);
            }

           /* if (config('pin_setting.credit_status')){
                $this->creditAdd($info);
            }*/

            if (method_exists($this->model,'addLog')){
                if (!empty($nextInfo)){
                    $this->model->addLog($perInfo,$nextInfo,2);
                }
            }
            DB::commit();
            return response()->json(['errcode'=>0,'errmsg'=>'ok']);
        }catch (\Exception $e){
            report($e);
            DB::rollBack();
            return response()->json(['errcode'=>40007,'errmsg'=>'修改失败']);
        }
    }

    protected function afterData($info, $requestData)
    {
        if (isset($requestData['id']) && $requestData['id']){
            $arr = $this->editData($info,json_decode($requestData['list'],true));
        }else{
            $arr = $this->addData($info,json_decode($requestData['list'],true));
        }
        if (!$arr[0]){
            return $arr;
        }
        $need = OrderList::where('oid',$info->id)->select('order_price','order_num')->get()->toArray();
        $count_price = 0;
        foreach($need as $val){
            $count_price = bcadd($count_price,bcmul($val['order_price'],$val['order_num'],2),2);//保证精度
        }
        Order::where('id',$info->id)->update(['order_money'=>$count_price]);
        return [true];
    }

    public function addData($info,$list)
    {
        if (!empty($list)){
            $data = [];
            $check_designated_inventory = config('pin_setting.check_designated_inventory');
            foreach ($list as $key => $value){
                if ($check_designated_inventory){
                    $spu = GoodsSpu::find($value['goods_spu_id']);
                    if ($spu->designated_inventory){
                        $oids = $this->model->where('send_time',$info->send_time)->where('id','<>',$info->id)->pluck('id');
                        $order_num = OrderList::whereIn('oid',$oids)->where('goods_spu_id',$value['goods_spu_id'])->sum('order_num');
                        if($spu->designated_inventory-$order_num < $value['order_num']){
                            //return $this->error(['40043','商品'.$value['name'].'超过指定库存']);
                            return [false,['40043','商品'.$value['name'].'超过指定库存']];
                        }
                    }
                }
                $data[$key] = $value;
                $data[$key]['oid'] = $info->id;
                $data[$key]['company_id'] = $this->company_id;
                $data[$key]['company_uid'] = $info->company_uid;
                $data[$key]['dispatch_user_id'] = $info->dispatch_user_id;
            }
            OrderList::insert($data);
            return [true];
        }
    }

    public function editData($info,$list)
    {
        if (!empty($list)){
            $data = [];
            $check_designated_inventory = config('pin_setting.check_designated_inventory');
            foreach ($list as $key => $value){
                if ($check_designated_inventory){
                    $spu = GoodsSpu::find($value['goods_spu_id']);
                    if ($spu->designated_inventory){
                        $oids = $this->model->where('send_time',$info->send_time)->where('id','<>',$info->id)->pluck('id');
                        $order_num = OrderList::whereIn('oid',$oids)->where('goods_spu_id',$value['goods_spu_id'])->sum('order_num');
                        if($spu->designated_inventory-$order_num < $value['order_num']){
                            //return $this->error(['40043','商品'.$value['name'].'超过指定库存']);
                            return [false,['40043','商品'.$value['name'].'超过指定库存']];
                        }
                    }
                }
                if (isset($value['id']) && $value['id']){
                    $save = OrderList::find($value['id']);
                    foreach ($value as $kk => $vv) {
                        $save->$kk = $vv;
                    }
                    $save->save();
                }else{
                    $data[$key] = $value;
                    $data[$key]['oid'] = $info->id;
                    $data[$key]['company_id'] = $this->company_id;
                    $data[$key]['company_uid'] = $info->company_uid;
                    $data[$key]['dispatch_user_id'] = $info->dispatch_user_id;
                }
            }
            if (!empty($data)){
                OrderList::insert($data);
            }
            return [true];
        }
    }

    public function info(Request $request)//BaseRequest
    {
        //dd($request);
        $id = $request->query('id');
        $info = $this->model->with(['orderList','member','companyName'])->find($id);
        $uid = $info->uid;
        $subAccount = Member::with(['address'])->select('id','nickname')->where(function ($query)use ($uid){
            $query->orWhere('pid',$uid)->orWhere('id',$uid);
        })->where('is_del',0)->where('status',1)->orderBy('pid','ASC')->get();

        $from = [
            0=>'后台',
            1=>'公众号',
            2=>'小程序',
            3=>'PC',
            4=>'APP'
        ];
        $pay_type = [0=>'未支付',1=>'已支付'];
        $is_print = [0=>'未打印',1=>'已打印'];
        $send_time = SendTime::selectRaw('CONCAT_WS("-",start_time,end_time) as times,id')->pluck('times','id')->toArray();
        $field = AdminListField::getListField(6);

        $logs = OperateLogs::with(['module','operate','type','admin'])
            ->where('main_id',$id)
            ->where('module',Order::OPERATE_PID)
            ->where('model',Order::MODEL)
            ->get();
        foreach ($logs as $log){//处理json字符串
            $content = json_decode($log->content,true);
            if (!empty($content)){
                $data = [];
                foreach ($content as $k => $v){
                    $data[] = substr($k,1,-1).':'.$v;
                }
                $log->content = json_encode($data,JSON_UNESCAPED_UNICODE);
            }

        }
        return $this->success(['info'=>$info,'subAccount'=>$subAccount,'order_status'=>$this->order_status,'from'=>$from,'pay_type'=>$pay_type,'is_print'=>$is_print,'send_time'=>$send_time,'field'=>$field,'logs'=>$logs]);
    }

    public function getOrderList(BaseRequest $request)
    {
        $id = $request->query('id');
        $uid = $request->query('uid');
        $member = Member::find($uid);
        $memberInfo  = MemberInfo::where('user_id',$uid)->first();
        $memberAddress  = MemberAddress::where('user_id',$uid)->first();
        $subAccount = Member::with(['address'])->select('id','nickname')->where(function ($query)use ($uid){
            $query->orWhere('pid',$uid)->orWhere('id',$uid);
        })->where('is_del',0)->where('status',1)->orderBy('pid','ASC')->get();
        $group_id = $memberInfo->group_id;
        $orderList = OrderList::with(['goods','goodsSpu'])->where('oid',$id)->get()->toArray();

        $allow_add_sold_out = config('pin_setting.allow_add_sold_out');
        foreach($orderList as $key => $val){
            if ($val['goods']['is_del'] || $val['goods_spu']['is_del']){
                unset($orderList[$key]);
                continue;
            }
            if (!$allow_add_sold_out){
                if (!$val['goods']['status'] || !$val['goods_spu']['status']){
                    unset($orderList[$key]);
                    continue;
                }
            }
            $price  = Goods::getPrice($uid,$group_id,$val['goods_id'],$val['goods_spu_id']);
            $orderList[$key]['order_price'] = $price;
        }
        return $this->success(['orderList'=>$orderList,'member'=>$member,'info'=>$memberInfo,'address'=>$memberAddress,'subAccount'=>$subAccount]);
    }

    public function setOrderStatus(BaseRequest $request)
    {
        $id = $request->get('id',0);
        $status = $request->get('status',0);
        //执行修改操作
        $result = $this->model->setStatus($id,$status);

        if ($result['code']){
            return $this->success();
        }else{
            return $this->error(['40035',$result['msg']]);
        }
    }

    protected function setRequestField($arr, $type = false)
    {
        if ($type === false) {
            $arr['order_sn'] = $this->sn('DD');
            $arr['company_id'] = $this->company_id;
            $arr['order_status'] = 1; //默认已审核
            $arr['admin_uid'] = Auth::user()->id;
        }
        //过滤字段
        if (isset($arr['list'])) unset($arr['list']);
        if (isset($arr['merge_status'])) unset($arr['merge_status']);
        if (isset($arr['ids'])) unset($arr['ids']);
        if (isset($arr['auto_merge_order'])) unset($arr['auto_merge_order']);
        if (isset($arr['auto_split_order'])) unset($arr['auto_split_order']);
        if (isset($arr['timeStamp'])) unset($arr['timeStamp']);
        if (isset($arr['sign'])) unset($arr['sign']);
        //处理字段
        $arr['send_time'] = strtotime($arr['send_time']);
        return $arr;
    }

    public function splitCate(BaseRequest $request)
    {
        $id = $request->query('id',0);
        $pids = OrderList::where('oid',$id)->distinct('pid')->pluck('pid');
        $category = GoodsCategory::select('id','title')->whereIn('id',$pids)->get();
        return $this->success(['category'=>$category]);
    }

    public function split(BaseRequest $request)
    {
        $id = $request->query('id',0);
        $cate = $request->query('cate','');
        $cate = json_decode($cate,true);
        if(!is_numeric($id)){
            return $this->error(['40016','参数错误']);
        }
        if (count($cate) == 0){
            return $this->error(['40016','参数错误,至少有一个分类']);
        }
        //订单信息
        $orderInfo = Order::with(['orderList'])->where('id',$id)->first();

        $orderArr = $orderInfo->toArray();
        //商品信息
        $item = collect($orderArr['order_list'])->transform(function($item){
            $item['item']['orderListId'] = $item['id'];
            $item['item']['order_num'] = $item['order_num'];
            $item['item']['order_price'] = $item['order_price'];
            $item['item']['sort_num'] = $item['sort_num'];
            $item['item']['sort_price'] = $item['sort_price'];
            $item['item']['pid'] = $item['pid'];
            return $item;
        })->pluck('item');
        $item = $item->groupBy('pid');
        try {
            DB::transaction(function ()use ($orderInfo,$cate,$item){
                foreach ($cate as $cate_id){
                    $newOrder = $orderInfo->replicate(['order_sn','is_print','delivery_fee','total_fee','order_money','send_money']);
                    $orderList = $item->get($cate_id);

                    $order_money = $send_money = 0;
                    foreach ($orderList as $list){
                        $order_money = bcadd($order_money,bcmul($list['order_num'],$list['order_price'],2),2);
                        $send_money = bcadd($send_money,bcmul($list['sort_num'],$list['sort_price'],2),2);
                    }

                    $orderNewInfo = Order::where('id',$orderInfo->id)->first();

                    if ($orderInfo->is_prior_payment){//前支付订单拆分逻辑
                        $newOrder->total_fee = $order_money;
                        $orderNewInfo->total_fee = bcsub($orderNewInfo->total_fee,$order_money,2);
                    }

                    $newOrder->order_sn = $this->sn('DD');
                    $newOrder->is_print = 0;
                    $newOrder->delivery_fee = 0;
                    $newOrder->order_money = $order_money;
                    $newOrder->send_money = $send_money;
                    $newOrder->save();

                    $orderNewInfo->order_money = bcsub($orderNewInfo->order_money,$order_money,2);
                    $orderNewInfo->send_money = bcsub($orderNewInfo->send_money,$send_money,2);
                    $orderNewInfo->save();

                    if($orderList->isEmpty()){
                        throw  new \Exception('没找到分类');
                    }else{
                        $orderListId = $orderList->pluck('orderListId');
                        OrderList::whereIn('id',$orderListId)->update(['oid'=>$newOrder->id]);
                    }
                }
            },5);
            Order::addLog($orderArr,[],5);
            return $this->success();
        }catch (\Exception $exception){
            report($exception);
            return $this->error(['40036','订单拆分失败']);
        }

    }

    public function merge(BaseRequest $request)
    {
        $ids = $request->query('ids','');
        $ids = json_decode($ids,true);
        //防止页面篡改
        $data = $this->model->with(['orderList'=>function($query){
            $query->select('id','oid','goods_id','goods_spu_id','order_num','order_price','sort_num','sort_price');
        }])->whereIn('id', $ids)->select('id','uid','zid','order_status','order_sn','send_time','order_money','send_money')->oldest('id')->get();
        if($data->count() <= 1){
            return $this->error(['40037','单个订单无法合并']);
        }
        $first = $data->shift();
        if($first->order_status > 1){
            return $this->error(['40038','订单不是待审核和备货中状态，无法合并']);
        }
        $first->send_carbon = Carbon::createFromTimestamp($first->send_time);

        $errors = [];
        $delOls = collect([]);
        $data->each(function($item) use(&$first,&$errors,&$delOls){

            if($item->order_status > 1){
                $errors = ['40038','订单不是待审核和备货中状态，无法合并'];
                return false;
            }
            if($item->uid != $first->uid || $item->zid != $first->zid){
                $errors = '';
                $errors = ['40039','订单不是同一个用户的，无法合并'];
                return false;
            }

            $item->send_time = Carbon::createFromTimestamp($item->send_time);
            if(!$first->send_carbon->isSameDay($item->send_time)){
                $errors = ['40040','配送日期不是同一天，无法合并'];
                return false;
            }
            $item->orderList->each(function($val) use(&$first,&$delOls,&$errors){
                $info = $first->orderList->firstWhere('goods_spu_id',$val->goods_spu_id);
                if (!empty($info)){
                    $first->orderList->firstWhere('id',$info->id)->order_num += $val->order_num;
                    $first->orderList->firstWhere('id',$info->id)->sort_num += $val->sort_num;
                    $delOls->push($val->id);
                }else{
                    $first->orderList->push($val);
                }
                $first->order_money += $val->order_num * $val->order_price;
                $first->send_money += $val->sort_num * $val->sort_price;
            });
        });
        if(!empty($errors)){
            return $this->error($errors);
        }
        unset($first->send_carbon);
        try {
            //订单ids
            $orderIds = $data->pluck('id');
            DB::transaction(function() use($delOls,$orderIds,$first){
                $first->orderList()->saveMany($first->orderList);
                $first->save();
                OrderList::destroy($delOls->toArray());
                Order::destroy($orderIds->toArray());
            },5);
            Order::addLog($first->toArray(),['content'=>$orderIds],4);
            return $this->success();
        }catch (\Exception $exception){
            return $this->error(['40041','订单合并失败']);
        }
    }

    public function checkOrder(BaseRequest $request)
    {
        $id = $request->query('id',0);
        $list = $request->query('list','');
        $list = json_decode($list,true);
        try {
            DB::transaction(function ()use($id,$list){
                $sign_for_money = 0;
                foreach ($list as $val){
                    $info = OrderList::find($val['id']);
                    if ($val['weight'] && $val['price']){
                        $info->weight = $val['weight'];
                        $info->price = $val['price'];
                        $sign_for_money = bcadd($sign_for_money,bcmul($val['weight'],$val['price'],2),2);
                    }else{
                        $info->weight = $info->sort_num;
                        $info->price = $info->sort_price;
                        $sign_for_money = bcadd($sign_for_money,bcmul($info->sort_num,$info->sort_price,2),2);
                    }
                    if ($val['remark']) $info->remark = $info->remark.$val['remark'];
                    $info->save();
                }
                $orderInfo = Order::find($id);
                //$orderInfo->order_status = 3;
                $perInfo = $orderInfo->getOriginal();
                $orderInfo->sign_for_money = $sign_for_money;
                $orderInfo->sign_for_time = time();
                $orderInfo->save();
                //$nextInfo = $orderInfo->getChanges();
                Order::addLog($perInfo,[],6,'checkOrder');
            },5);
            return $this->success();
        }catch (\Exception $exception){
            return $this->error(['40042','订单验收失败']);
        }
    }

    public function getMemberInfo(BaseRequest $request)
    {
        $id = $request->query('id',0);
        $info = MemberInfo::where('user_id',$id)->first();
        $address = MemberAddress::where('user_id',$id)->first();
        $subAccount = Member::with(['address'])->select('id','nickname')->where(function ($query)use ($id){
            $query->orWhere('pid',$id)->orWhere('id',$id);
        })->where('is_del',0)->where('status',1)->orderBy('pid','ASC')->get();
        return $this->success(['info'=>$info,'address'=>$address,'subAccount'=>$subAccount]);
    }

    public function copyList(BaseRequest $request)
    {
        $uid = $request->query('uid',0);
        $order_sn = $request->query('order_sn','');
        $list = $this->model->select('id','order_sn','uid','created_at')->where('uid',$uid)->when($order_sn,function ($query)use ($order_sn){
            $query->where('order_sn','like',"%$order_sn%");
        })->whereIn('order_status',[1,2,3])->orderBy('id',"DESC")->limit(10)->get();
        return $this->success(['list'=>$list]);
    }
}
